package com.xin.springbootjurisdiction.service.impl;

import com.xin.springbootjurisdiction.dataobject.ModuleInfo;
import com.xin.springbootjurisdiction.repository.ModuleInfoRepository;
import com.xin.springbootjurisdiction.service.ModuleInfoService;
import com.xin.springbootjurisdiction.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * 模块管理
 */
@Service
@Slf4j
public class ModuleInfoServiceImpl implements ModuleInfoService {
    @Autowired
    private ModuleInfoRepository moduleInfoRepository;

    /**
     * 创建模块
     *
     * @param moduleInfo
     * @return
     */
    @Override
    @Transactional
    public ModuleInfo create(ModuleInfo moduleInfo) {
        if (ObjectUtils.isEmpty(moduleInfo)) {
            log.info("【添加模块】参数不能为空!");
            return null;
        }
        //添加随机的ID
        moduleInfo.setModuleId(KeyUtil.genUniqueKey());
        ModuleInfo info = moduleInfoRepository.save(moduleInfo);
        if (!ObjectUtils.isEmpty(info)) {
            return info;
        }
        return null;
    }

    /**
     * 删除模块
     *
     * @param moduleId
     * @return
     */
    @Override
    @Transactional
    public boolean delete(String moduleId) {
        ModuleInfo moduleInfo = findOne(moduleId);
        if (ObjectUtils.isEmpty(moduleInfo)) {
            return false;
        }
        moduleInfoRepository.delete(moduleInfo);
        return true;
    }

    /**
     * 更新模块
     *
     * @param moduleInfo
     * @return
     */
    @Override
    @Transactional
    public ModuleInfo update(ModuleInfo moduleInfo) {
        //查看参数是否为空
        if (ObjectUtils.isEmpty(moduleInfo)) {
            return null;
        }
        //查看是否存在该用户
        ModuleInfo one = findOne(moduleInfo.getModuleId());
        if (ObjectUtils.isEmpty(one)) {
            return null;
        }
        one.setName(moduleInfo.getName());
        ModuleInfo save = moduleInfoRepository.save(one);
        if (!ObjectUtils.isEmpty(save)) {
            return save;
        }
        return null;
    }

    /**
     * 查找模块
     *
     * @param moduleId
     * @return
     */
    @Override
    public ModuleInfo findOne(String moduleId) {

        if (StringUtils.isEmpty(moduleId)) {
            return null;
        }
        ModuleInfo moduleInfo = moduleInfoRepository.findOne(moduleId);
        if (!ObjectUtils.isEmpty(moduleInfo)){
            return moduleInfo;
        }
        return null;
    }
}
